//
//  FlightCityListController.m
//  ELife
//
//  Created by xiaozhi on 11-5-24.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FlightCityListController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "ELifeAppDelegate.h"

NSArray *LIST_TITLE;

@implementation FlightCityListController
@synthesize cityTableView, _owner;

- (id)init
{
    self = [self initWithNibName:@"FlightCityListController" bundle:nil];
    LIST_TITLE = [NSArray arrayWithObjects:@"热点城市", @"A-F", @"G-J", @"K-N", @"P-W", @"X-Z", nil];
    
    NSInteger groupCount = [LIST_TITLE count];

    _citySections = [[NSMutableArray alloc]initWithCapacity:groupCount];
    for (NSInteger index = 0; index < groupCount; index++) {
        CitySection *citySection = [[CitySection alloc]initWithTitle:[LIST_TITLE objectAtIndex:index]];
        [_citySections addObject:citySection];
    }
    
    return self;
}

- (void)dealloc
{
    [cityTableView release];
    [_citySections release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - network
- (void)requestFlightCityList
{
    
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"get_airline_airport" forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestFlightCityListFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];

}

- (NSInteger)getGroupIndexWithLetter:(NSString *)letter
{
    char charLetter = [letter characterAtIndex:0];
    NSInteger index = 0;
    if ((charLetter >= 'A' && charLetter <= 'F') || (charLetter >= 'a' && charLetter <= 'f')) {
        index = 1;
    } else if ((charLetter >= 'G' && charLetter <= 'J') || (charLetter >= 'g' && charLetter <= 'j')) {
        index = 2;
    } else if ((charLetter >= 'K' && charLetter <= 'N') || (charLetter >= 'k' && charLetter <= 'n')) {
        index = 3;
    } else if ((charLetter >= 'P' && charLetter <= 'W') || (charLetter >= 'p' && charLetter <= 'w')) {
        index = 4;
    } else if ((charLetter >= 'X' && charLetter <= 'Z') || (charLetter >= 'x' && charLetter <= 'z')) {
        index = 5;
    }
    
    return index;
}

- (void)fillCitySectionsWithFlightCity:(FlightCity *)flightCity
{
    CitySection *citySection = nil;
    // isHotCity ?
    if ([flightCity._isHot isEqualToString:IS_HOT]) {
        citySection = [_citySections objectAtIndex:0];
    } else {
        NSString *firstLetter = flightCity._cityFirstLetter;
        NSInteger groupIndex = [self getGroupIndexWithLetter:firstLetter];
        citySection = [_citySections objectAtIndex:groupIndex];
    }
    
    [citySection.cityList addObject:flightCity];
}


- (void)requestFlightCityListFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
    //某个具体节点的文本内容
    GDataXMLElement* citiesElement = [[bodyElement elementsForName:@"airports"]objectAtIndex:0];
    
    NSArray *cityArr = [citiesElement children];
    
    for (int i = 0; i < [cityArr count]; i++) {
        GDataXMLElement *item = [cityArr objectAtIndex:i];
        NSLog(@"----------flight cityList ITEM:%@", item);
        /*
         airma = 城市的3位码
         air_city = 城市名称
         airport_name = 飞机场名称
         airport_type = 0代表国内机场
         is_hot = 是否热点城市  0不是热点城市  1是热点
         letter = 拼音首字母
         */
        FlightCity *flightCity = [[FlightCity alloc]init];
        flightCity._cityCode = [[[item elementsForName:@"airma"]objectAtIndex:0]stringValue];
        flightCity._cityName = [[[item elementsForName:@"air_city"]objectAtIndex:0]stringValue];
        flightCity._airportName = [[[item elementsForName:@"airport_name"]objectAtIndex:0]stringValue];
        flightCity._airportType = [[[item elementsForName:@"airport_type"]objectAtIndex:0]stringValue];
        flightCity._isHot = [[[item elementsForName:@"is_hot"]objectAtIndex:0]stringValue];
        flightCity._cityFirstLetter = [[[item elementsForName:@"letter"]objectAtIndex:0]stringValue];
        
        [self fillCitySectionsWithFlightCity:flightCity];
        [flightCity release];
    }
    
    [cityTableView reloadData];
}

- (void)iRequestFailed
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"查询城市失败" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    [[ELifeAppDelegate App] hideProgressDialog];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [[UIColor alloc]
                                 initWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    
    [self requestFlightCityList];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_citySections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CitySection *citySection= (CitySection *)[_citySections objectAtIndex:section];
    
    // 如果没展开 则只返回标题
    if (citySection.isExpand == NO) {
        return 1;
    }
    
    return [citySection.cityList count] + 1;
}

- (CitySection *)getCitySectionByIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    CitySection *citySection = [_citySections objectAtIndex:section];
    return citySection;
}

// get city name
- (NSString *)getCityNameByIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    
    CitySection *citySection = [self getCitySectionByIndexPath:indexPath];
    
    // 如果没展开 则只返回标题 或者row为0则只返回标题
    if (citySection.isExpand == NO || row == 0) {
        return citySection.title;
    }
    
    FlightCity *flightCity = [citySection.cityList objectAtIndex:row - 1];
    
    return flightCity._cityName;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    NSString *cityName = [self getCityNameByIndexPath:indexPath];
    
    cell.textLabel.text = cityName;
    // 居中对其
    cell.textLabel.textAlignment = UITextAlignmentCenter;
    
    
    // 第一级标签颜色改变
    if (indexPath.row == 0) {
        cell.textLabel.textColor = [UIColor blueColor];
    } else {
        cell.textLabel.textColor = [UIColor grayColor];
    }
    return cell;
}


#pragma mark - Table view delegate

- (void)expandSection:(NSInteger)section
{
    CitySection *citySection = [_citySections objectAtIndex:section];
    citySection.isExpand = !(citySection.isExpand);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 如果选中的是第一级的菜单项
    if (indexPath.row == 0) {
        [self expandSection:indexPath.section];
        [tableView reloadData];
        return;
    }
    
    // 如果是2级菜单
    if (_owner != nil
        && _onSelected != nil) {
        CitySection *citySection = [self getCitySectionByIndexPath:indexPath];
        FlightCity *flightCity = [citySection.cityList objectAtIndex:indexPath.row - 1];
        [_owner performSelector:_onSelected withObject:flightCity];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)addTarget:(id)owner action:(SEL)action
{
    self._owner = owner;
    _onSelected = action;
}

@end


@implementation CitySection
@synthesize cityList, isExpand, title = _title;

- (id)initWithTitle:(NSString *)sectionTitle
{
    self = [self init];
    if (self) {
        _title = sectionTitle;
        cityList = [[NSMutableArray alloc]initWithCapacity:20];
    }
       
    return self;
}

- (void)dealloc
{
    [_title release];
    [cityList release];
    [super dealloc];
}
@end

@implementation FlightCity
@synthesize _cityCode, _cityName, _airportName, _airportType, _isHot, _cityFirstLetter;

- (void)dealloc
{
    [_airportType release];
    [_isHot release];
    [_cityCode release];
    [_cityName release];
    [_airportName release];
    [_cityFirstLetter release];
    [super dealloc];
}

@end
